<template>
  <div class="data-map-view">
    <!-- 地图容器 -->
    <div ref="mapContainer" class="map-container"></div>
    
    <!-- 地图工具栏 -->
    <!-- <div class="map-toolbar">
      <a-button-group>
        <a-button @click="zoomIn" icon="plus" title="放大"></a-button>
        <a-button @click="zoomOut" icon="minus" title="缩小"></a-button>
        <a-button @click="resetView" icon="reload" title="重置视图"></a-button>
        <a-button @click="toggleFullscreen" :icon="isFullscreen ? 'fullscreen-exit' : 'fullscreen'" :title="isFullscreen ? '退出全屏' : '全屏'"></a-button>
        <a-button @click="refreshData" icon="sync" title="刷新数据" :loading="loading"></a-button>
      </a-button-group>
    </div> -->

    <!-- 聚合控制 -->
    <!-- <div class="cluster-control">
      <a-switch 
        v-model="enableCluster" 
        @change="toggleCluster"
        checked-children="聚合" 
        un-checked-children="散点"
      />
    </div> -->

    <!-- Mec信息弹窗 -->
    <a-modal
      v-model="infoVisible"
      title="Mec详情"
      :footer="null"
      width="600px"
    >
      <div v-if="selectedDataItem" class="data-item-info">
        <a-descriptions :column="2" bordered>
          <a-descriptions-item label="设备编号">{{ selectedDataItem.deviceId }}</a-descriptions-item>
          <a-descriptions-item label="序列号">{{ selectedDataItem.serialNumber }}</a-descriptions-item>
          <a-descriptions-item label="厂商">{{ selectedDataItem.manufacturerId_dictText }}</a-descriptions-item>
          <a-descriptions-item label="路侧杆件">{{ selectedDataItem.crossName + '-' + selectedDataItem.polePositionType_dictText }}</a-descriptions-item>
          <a-descriptions-item label="所属道路">{{ selectedDataItem.roadName }}</a-descriptions-item>
          <a-descriptions-item label="所属路口">{{ selectedDataItem.crossName }}</a-descriptions-item>
          <a-descriptions-item label="状态" :span="2">
            <a-tag :color="selectedDataItem.onlineState === 1 ? 'green' : 'red'">
              {{ selectedDataItem.onlineState_dictText }}
            </a-tag>
          </a-descriptions-item>
          <a-descriptions-item label="经纬度" :span="2">
            {{ selectedDataItem.lng }}, {{ selectedDataItem.lat }}
          </a-descriptions-item>
        </a-descriptions>
      </div>
    </a-modal>

    <!-- 聚合弹窗 -->
    <a-modal
      v-model="clusterVisible"
      title="聚合Mec列表"
      :footer="null"
      width="800px"
    >
      <a-table
        v-if="clusterDataItems.length > 0"
        :columns="clusterColumns"
        :data-source="clusterDataItems"
        :pagination="false"
        size="small"
        @row-click="onClusterRowClick"
      >
        <template slot="status" slot-scope="text">
          <a-tag :color="text === '在线' ? 'green' : 'red'">
            {{ text }}
          </a-tag>
        </template>
        <template slot="action" slot-scope="text, record">
          <a @click="locateItem(record)">定位</a>
        </template>
      </a-table>
    </a-modal>
  </div>
</template>

<script>
import Vue from 'vue'
import { getAction } from '@/api/manage'
import { gws84 } from '@/views/components/map/js/BD09-WGS84'

export default {
  name: 'DataMapView',
  props: {
    // 地图中心点
    mapCenter: {
      type: Object,
      default: () => ({
        lng: 117.07149171065725,
        lat: 36.89521254833693
      })
    },
    // 地图缩放级别
    zoom: {
      type: Number,
      default: 15
    },
    // 地图配置
    mapConfig: {
      type: Object,
      default: () => ({
        enableScrollWheelZoom: true,
        enableDragging: true,
        enableDoubleClickZoom: true
      })
    },
    // 查询参数
    queryParams: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    return {
      map: null, // 地图实例
      markers: [], // 标记点数组
      itemData: [], // Mec数据
      selectedDataItem: null, // 选中的Mec
      infoVisible: false, // 信息弹窗显示状态
      clusterVisible: false, // 聚合弹窗显示状态
      clusterDataItems: [], // 聚合Mec列表
      isFullscreen: false, // 全屏状态
      loading: false, // 加载状态
      enableCluster: false, // 是否启用聚合
      markerClusterer: null, // 聚合器实例
      iconSrc: 'assets/operationalSupervision/map/', // 图标路径
      markerMap: new Map(), // 标记点映射
      
      // 聚合列表表格配置
      clusterColumns: [
        {
          title: '设备编号',
          dataIndex: 'deviceCode',
          key: 'deviceCode',
          width: 120
        },
        {
          title: '设备类型',
          dataIndex: 'deviceType',
          key: 'deviceType',
          width: 100
        },
        {
          title: '状态',
          dataIndex: 'status',
          key: 'status',
          width: 80,
          scopedSlots: { customRender: 'status' }
        },
        {
          title: '所属道路',
          dataIndex: 'roadName',
          key: 'roadName',
          width: 150
        },
        {
          title: '所属路口',
          dataIndex: 'crossName',
          key: 'crossName',
          width: 150
        },
        {
          title: '操作',
          key: 'action',
          width: 80,
          scopedSlots: { customRender: 'action' }
        }
      ]
    }
  },
  watch: {
    // 监听查询参数变化
    queryParams: {
      handler() {
        this.loadItemData()
      },
      deep: true
    }
  },
  mounted() {
    this.initMap()
  },
  beforeDestroy() {
    if (this.map) {
      this.map.destroy()
    }
  },
  methods: {
    // 初始化地图
    initMap() {
      try {
        this.map = new BMapGL.Map(this.$refs.mapContainer)
        
        // 设置地图中心点和缩放级别
        const centerPoint = new BMapGL.Point(this.mapCenter.lng, this.mapCenter.lat)
        this.map.centerAndZoom(centerPoint, this.zoom)
        
        // 配置地图功能
        if (this.mapConfig.enableScrollWheelZoom) {
          this.map.enableScrollWheelZoom(true)
        }
        if (this.mapConfig.enableDragging) {
          this.map.enableDragging()
        }
        if (this.mapConfig.enableDoubleClickZoom) {
          this.map.enableDoubleClickZoom()
        }
        
        // 设置地图样式
        this.map.setMapType(BMAP_NORMAL_MAP)
        this.map.getPanes().markerPane.style.zIndex = 500
        
        // 初始化聚合器
        // this.initMarkerClusterer()
        
        // 触发地图初始化完成事件
        this.$emit('map-ready', this.map)
        
        // 加载Mec数据
        this.loadItemData()
        
      } catch (error) {
        console.error('地图初始化失败:', error)
        this.$message.error('地图初始化失败，请检查百度地图API是否正确加载')
      }
    },
    
    // 初始化聚合器
    initMarkerClusterer() {
    //   if (window.BMapLib && window.BMapLib.MarkerClusterer) {
        this.markerClusterer = new BMapGL.MarkerClusterer(this.map, {
          markers: [],
          girdSize: 60,
          maxZoom: 18,
          minClusterSize: 2,
         
        })
        console.log(this.markerClusterer)
        // 监听聚合点击事件
        this.markerClusterer.addEventListener('clusterclick', (cluster) => {
          this.onClusterClick(cluster)
        })
    //   }
    },
    
    // 加载Mec数据
    async loadItemData() {
      this.loading = true
      try {
        const params = {
          pageNo: 1,
          pageSize: 10000, // 获取全量数据
          ...this.queryParams
        }
        
        const response = await getAction('/basicinfo/roadsideDevice/mec/listByCondition', params)
        
        if (response.success) {
          this.itemData = response.result.records || []
         
          this.updateDataItemMarkers()
          this.$message.success(`成功加载 ${this.itemData.length} 个Mec`)
        } else {
          this.$message.error('加载Mec数据失败: ' + response.message)
        }
      } catch (error) {
        console.error('加载Mec数据失败:', error)
        this.$message.error('加载Mec数据失败')
      } finally {
        this.loading = false
      }
    },
    
    // 更新Mec标记
    updateDataItemMarkers() {

      if (!this.map || !this.itemData) return
      // 清除现有标记
      this.clearMarkers()
      
      this.itemData.forEach(item => {
        this.addDataItemMarkers(item)
      })
      
      // 更新聚合器
      // if (this.enableCluster && this.markerClusterer) {
      //   this.markerClusterer.clearMarkers()
      //   this.markerClusterer.addMarkers(this.markers)
      // }
      
      console.log(`已添加 ${this.markers.length} 个Mec标记`)
    },
    
    // 添加Mec标记
    addDataItemMarkers(dataItem) {
        console.log('添加Mec标记:', dataItem)
      if (!dataItem.lng || !dataItem.lat) {
        console.warn('Mec缺少经纬度信息:', dataItem)
        return
      }
      
      try {
        // 坐标转换（如果需要）
        let coordinates = {
          lng: parseFloat(dataItem.lng),
          lat: parseFloat(dataItem.lat)
        }
        
        // 如果是WGS84坐标，需要转换为百度坐标
        if (dataItem.coordinateType === 'WGS84') {
          const gcj02Point = gws84().wgs84togcj02(coordinates.lng, coordinates.lat)
          coordinates = gws84().gcj02tobd09(gcj02Point.lng, gcj02Point.lat)
        }
        
        // 创建标记点
        const point = new BMapGL.Point(coordinates.lng, coordinates.lat)
        
        // 根据Mec状态选择图标
        const iconName = dataItem.status === '在线' ? 'dataItem_online' : 'dataItem_offline'
        const iconSize = new BMapGL.Size(32, 32)
        
        const icon = new BMapGL.Icon(
          require(`@/assets/operationalSupervision/map/point-icon4.png`),
          iconSize,
          {
            imageSize: iconSize,
            anchor: new BMapGL.Size(16, 32)
          }
        )
        
        const marker = new BMapGL.Marker(point, { icon })
        marker.itemData = dataItem
        marker.setZIndex(9999)
        console.log(marker)
        // 添加事件监听
        marker.addEventListener('click', (e) => {
          this.onMarkerClick(e.target.itemData)
        })
        
        marker.addEventListener('mouseover', (e) => {
          this.showItemDataTooltip(e.target.itemData, e.point)
        })
        
        marker.addEventListener('mouseout', () => {
          this.hideTooltip()
        })
        
        // 添加到数组和映射
        this.markers.push(marker)
        this.markerMap.set(dataItem.id, marker)
        
        // 如果不启用聚合，直接添加到地图
        if (!this.enableCluster) {
          this.map.addOverlay(marker)
        }
        
      } catch (error) {
        console.error('添加Mec标记失败:', error, dataItem)
      }
    },
    
    // 聚合点击事件
    onClusterClick(cluster) {
      const markers = cluster.getMarkers()
      this.clusterDataItems = markers.map(marker => marker.itemData)
      this.clusterVisible = true
    },
    
    // 聚合列表行点击
    onClusterRowClick(record) {
      this.selectedDataItem = record
      this.infoVisible = true
      this.clusterVisible = false
    },
    
    // 定位Mec
    locateItem(item) {
      const marker = this.markerMap.get(item.id)
      if (marker) {
        const point = marker.getPosition()
        this.map.centerAndZoom(point, Math.max(this.map.getZoom(), 16))
        this.clusterVisible = false
        
        // 高亮效果
        setTimeout(() => {
          this.onMarkerClick(item)
        }, 500)
      }
    },
    
    // 切换聚合模式
    toggleCluster(enabled) {
      this.enableCluster = enabled
      
      if (enabled) {
        // 启用聚合
        this.markers.forEach(marker => {
          this.map.removeOverlay(marker)
        })
        if (this.markerClusterer) {
          this.markerClusterer.addMarkers(this.markers)
        }
      } else {
        // 禁用聚合
        if (this.markerClusterer) {
          this.markerClusterer.clearMarkers()
        }
        this.markers.forEach(marker => {
          this.map.addOverlay(marker)
        })
      }
    },
    
    // 标记点击事件
    onMarkerClick(item) {
      this.selectedDataItem = item
      this.infoVisible = true
      this.$emit('item-selected', item)
    },
    
    // 显示Mec提示信息
    showItemDataTooltip(item, point) {
      console.log('显示Mec提示信息:', item, point)
      const content = `
        <div class="data-item-tooltip">
          <div class="tooltip-title">${item.deviceId}</div>
          <div class="tooltip-content">
            <div>类型: ${item.deviceType}</div>
            <div>状态: <span class="status ${item.onlineState === 1 ? 'online' : 'offline'}">${item.onlineState_dictText}</span></div>
            <div>位置: ${item.roadName || '未知'}</div>
          </div>
        </div>
      `
      
      const label = new BMapGL.Label(content, {
        position: point,
        offset: new BMapGL.Size(10, -40)
      })
      
      label.setStyle({
        border: 'none',
        backgroundColor: 'rgba(0, 0, 0, 0.8)',
        color: '#fff',
        borderRadius: '4px',
        padding: '8px',
        fontSize: '12px',
        whiteSpace: 'nowrap',
        cursor: 'pointer'
      })
      
      this.map.addOverlay(label)
      this.currentTooltip = label
    },
    
    // 隐藏提示信息
    hideTooltip() {
      if (this.currentTooltip) {
        this.map.removeOverlay(this.currentTooltip)
        this.currentTooltip = null
      }
    },
    
    // 清除所有标记
    clearMarkers() {
        if(this.markers.length>0){
            this.markers.forEach(marker => {
                this.map.removeOverlay(marker)
            })
            this.markers = []
            this.markerMap.clear()
        }
     
      
        if (this.markerClusterer) {
            this.markerClusterer.clearMarkers()
        }
    },
    
    // 刷新数据
    refreshData() {
      this.loadItemData()
    },
    
    // 地图工具栏方法
    zoomIn() {
      if (this.map) {
        this.map.zoomIn()
      }
    },
    
    zoomOut() {
      if (this.map) {
        this.map.zoomOut()
      }
    },
    
    resetView() {
      if (this.map) {
        const centerPoint = new BMapGL.Point(this.mapCenter.lng, this.mapCenter.lat)
        this.map.centerAndZoom(centerPoint, this.zoom)
      }
    },
    
    toggleFullscreen() {
      const element = this.$el
      if (!this.isFullscreen) {
        if (element.requestFullscreen) {
          element.requestFullscreen()
        } else if (element.webkitRequestFullscreen) {
          element.webkitRequestFullscreen()
        } else if (element.mozRequestFullScreen) {
          element.mozRequestFullScreen()
        }
      } else {
        if (document.exitFullscreen) {
          document.exitFullscreen()
        } else if (document.webkitExitFullscreen) {
          document.webkitExitFullscreen()
        } else if (document.mozCancelFullScreen) {
          document.mozCancelFullScreen()
        }
      }
      this.isFullscreen = !this.isFullscreen
    },
    
    // 获取地图实例
    getMapInstance() {
      return this.map
    },
    
    // 获取Mec数据
    getItemData() {
      return this.itemData
    }
  }
}
</script>

<style scoped lang="less">
.data-map-view {
  position: relative;
  width: 100%;
  height: 100%;
  
  .map-container {
    width: 100%;
    height: 100%;
  }
  
  .map-toolbar {
    position: absolute;
    top: 10px;
    right: 10px;
    z-index: 1000;
    background: rgba(255, 255, 255, 0.9);
    border-radius: 4px;
    padding: 4px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  }
  
  .cluster-control {
    position: absolute;
    top: 10px;
    left: 10px;
    z-index: 1000;
    background: rgba(255, 255, 255, 0.9);
    border-radius: 4px;
    padding: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  }
  
  .data-item-info {
    .ant-descriptions {
      margin-top: 16px;
    }
  }
}

// 全局样式（用于地图内的元素）
:global(.data-item-tooltip) {
  .tooltip-title {
    font-weight: bold;
    margin-bottom: 4px;
    font-size: 14px;
  }
  
  .tooltip-content {
    font-size: 12px;
    line-height: 1.4;
    
    .status {
      &.online {
        color: #52c41a;
      }
      
      &.offline {
        color: #ff4d4f;
      }
    }
  }
}
</style>